<template>
  <div>
    <c-section title="任务基础信息">
      <c-list :column="3" label-width="140px">
        <c-list-item label="任务类型" dict-type-code="TASK_TYPE" :value="detail.taskType" />
        <c-list-item label="数据来源" dict-type-code="DATA_SOURCE" :value="detail.dataSource" />
        <c-list-item label="任务来源单据" clickable :value="detail.sourceCode" @click.native="toSource(detail.sourceCode)" />
        <c-list-item label="门店建设项目号" :value="detail.constCode" />
        <c-list-item label="设计范围" dict-type-code="DECORATION_RANGE" :value="detail.designRange || detail.decorationRange" />
        <c-list-item label="装修形式" dict-type-code="DECORATION_FORM" :value="detail.decorationType || detail.decorationForm" />
        <c-list-item label="是否需要复尺" dict-type-code="BOOLEANS" :value="detail.isNeedResurvey" />
        <c-list-item label="是否完成复尺" dict-type-code="BOOLEANS" :value="detail.isEndResurvey" />
        <c-list-item label="不复尺设计摆场" dict-type-code="UNRESURVEY_STATE" :value="detail.unresurveyDesignSetup" />
        <c-list-item label="不复尺设计施工" dict-type-code="UNRESURVEY_STATE" :value="detail.unresurveyDesignConst" />
        <c-list-item label="是否KA卖场" dict-type-code="BOOLEANS" :value="detail.isKaMarket" />

        <!-- 1、新增页面、待分配页面，“是否重复设计、重复设计原因”调整到任务基础信息中展示；  -->
        <c-list-item label="是否含重复设计" dict-type-code="BOOLEANS" :value="detail.haveRedesign">
          <!-- <c-dict-select v-model="formData.haveRedesign" dict-type-code="BOOLEANS" placeholder="是否含重复设计" /> -->
        </c-list-item>
        <c-list-item v-if="detail.haveRedesign == '1'" dict-type-code="REDESIGN_REASON" label="重复设计原因" :value="detail.redesignReason">
          <!-- <c-dict-select v-model="formData.redesignReason" dict-type-code="REDESIGN_REASON" placeholder="重复设计原因" /> -->
        </c-list-item>
        <c-list-item label="是否需要门头效果图" dict-type-code="BOOLEANS" :value="designDetail.isNeedRendering" />

        <c-list-item label="图纸紧急程度" dict-type-code="PIC_URGENT_LEVEL" :value="detail.picUrgentLevel" />
        <c-list-item label="所属门店编码" :value="shopDetail.shopCode" />
        <c-list-item label="所属门店" :value="shopDetail.shopName" />
        <c-list-item label="所属客户编码" :value="shopDetail.clientCode" />
        <c-list-item label="所属客户" :value="shopDetail.clientName" />
        <c-list-item label="所属办事处" :value="shopDetail.officeName" />
      </c-list>
      <!-- 十月优化START -->
      <Area :detail="detail" :pic-detail="picDetail" :design-detail="designDetail" />
      <!-- 十月优化END -->
      <c-list :column="3" label-width="140px">
        <c-list-item label="申请说明" :span="3" :value="detail.taskDesc || detail.applyDesc" />
      </c-list>
    </c-section>
    <c-section title="任务分配">
      <!-- 设计申请 -->
      <c-list ref="form" :model="formData" :rules="formRules" :column="3" label-width="145px">
        <c-list-item label="任务分配结果" prop="distributeResult">
          <c-dict-select v-model="formData.distributeResult" dict-type-code="DISTRIBUTE_RESULT" placeholder="任务分配结果" />
        </c-list-item>
        <c-list-item v-if="formData.distributeResult === 'B'" label="任务终止原因" :span="3" prop="endReason">
          <el-input v-model="formData.endReason" type="textarea" :autosize="{minRows: 3}" placeholder="任务说明" maxlength="1024" show-word-limit clearable />
        </c-list-item>
        <template v-if="formData.distributeResult !== 'B'">
          <c-list-item label="首次分配时间" :value="formData.distributeTime || detail.nowTime" />
          <c-list-item label="店面等级" prop="shopLevelCode">
            <c-dict-select v-model="formData.shopLevelCode" dict-type-code="SHOP_LEVEL_CODE" placeholder="店面等级" />
          </c-list-item>
          <c-list-item label="是否重点市场" prop="isFocusMarket">
            <c-dict-select v-model="formData.isFocusMarket" dict-type-code="BOOLEANS" placeholder="是否重点市场" />
          </c-list-item>
          <c-list-item label="设计单位" prop="designUnitCode">
            <c-single-dialog
              ref="designUnitCode"
              v-model="formData.designUnitCode"
              :props="{label:'orgName',value:'orgCode'}"
              :label.sync="formData.designUnitName"
              :focus-query="true"
              :multiple="false"
              :config="{
                title:'设计单位',
                width:'600px',
                interfacePath:'/slm-admin/api/v1/user/orgTreeByType?type=9',
                method:'get',
                filtersRaw:[],
                paramsRaw:{},
                setting:[
                  {prop:'orgCode',title:'编码'},
                  {prop:'orgName',title:'名称'},
                ]
              }"
              @change="changeUnitHandle"
            />
          </c-list-item>
          <template v-if="(detail.designRange || '').includes('DOOR')">
            <c-list-item key="dheadPicDesignType" label="门头图纸设计类型" prop="dheadPicDesignType">
              <c-dict-select v-model="formData.dheadPicDesignType" exclude="GH,BC" dict-type-code="PIC_TYPE" placeholder="门头图纸设计类型" @change="v=>changeHandle(v, 'DOOR')" />
            </c-list-item>
            <c-list-item v-if="showTime && detail.designRange === 'DOOR'" key="dheadExpectCompleteTime" label="门头预计设计完成时间" prop="dheadExpectCompleteTime">
              <el-date-picker
                v-model="formData.dheadExpectCompleteTime"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
                clearable
              />
            </c-list-item>
          </template>
          <template v-if="(detail.designRange || '').includes('STORES')">
            <c-list-item key="shopPicDesignType" label="卖场图纸设计类型" prop="shopPicDesignType">
              <c-dict-select v-model="formData.shopPicDesignType" exclude="PB" dict-type-code="PIC_TYPE" placeholder="卖场图纸设计类型" @change="v=>changeHandle(v, 'STORES')" />
            </c-list-item>
            <c-list-item v-if="showTime" key="marketExpectCompleteTime" label="卖场预计设计完成时间" prop="marketExpectCompleteTime">
              <el-date-picker
                v-model="formData.marketExpectCompleteTime"
                type="date"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期"
                clearable
              />
            </c-list-item>
          </template>
        </template>
      </c-list>
      <div class="btn-container">
        <c-button @click="cancelHandle">取消</c-button>
        <c-button type="primary" @click="submitHandle">提交</c-button>
      </div>
    </c-section>
  </div>
</template>
<script>
import { getShopDesignTaskWholeInfo, shopConstructPage, postConfigTimeLimitPage, basicsInfo, getShopDesignTaskInfo, putTaskAllocation, getShopDesignInfo } from '@/api/shopDesignTask'
import { SLMDict } from '@/api/dataDict'
import { getPath, getPicturePage } from './getPath'
import { concatObj } from '@/utils'
import Area from './components/Area'
export default {
  name: 'ShopDesignTaskAllocation',
  components: {
    Area
  },
  data() {
    return {
      taskDetail: {},
      designDetail: {},
      picDetail: {},
      shopDetail: {},
      wholeInfo: {},
      PIC_TYPE: [],
      formData: {
        distributeResult: '',
        endReason: '',
        shopLevelCode: '',
        isFocusMarket: '',
        designUnitCode: '',
        designUnitName: '',
        haveRedesign: '',
        redesignReason: '',
        dheadPicDesignType: '',
        dheadExpectCompleteTime: '',
        shopPicDesignType: '',
        marketExpectCompleteTime: '',
        designRange: '',
        otherCode: ''
      },
      formRules: {
        distributeResult: [{ required: true, message: '请选择分配结果', trigger: 'change' }],
        endReason: [{ required: true, message: '请输入任务终止原因', trigger: 'change' }],
        shopLevelCode: [{ required: true, message: '请选择门店等级', trigger: 'change' }],
        isFocusMarket: [{ required: true, message: '请选择是否重点市场', trigger: 'change' }],
        designUnitCode: [{ required: true, message: '请选择施工单位', trigger: 'change' }],
        haveRedesign: [{ required: true, message: '请选择是否包含重复设计', trigger: 'change' }],
        redesignReason: [{ required: true, message: '请选择重复设计原因', trigger: 'change' }],
        dheadPicDesignType: [{ required: false, message: '请选择门头图纸设计类型', trigger: 'change' }],
        dheadExpectCompleteTime: [{ required: true, message: '请选择门头预计设计完成时间', trigger: 'change' }],
        shopPicDesignType: [{ required: false, message: '请选择门店图纸设计类型', trigger: 'change' }],
        marketExpectCompleteTime: [{ required: true, message: '请选择卖场预计设计完成时间', trigger: 'change' }]
      }
    }
  },
  computed: {
    detail() {
      const t = concatObj(this.picDetail, this.taskDetail, this.wholeInfo, this.designDetail, this.shopDetail)
      // 2、除任务类型为“设计变更”的设计任务，“是否重复设计、重复设计原因”接收BPM传值以外，
      // 其余类型的设计任务“是否含重复设计”都默认显示“否”；
      if (t.taskType !== 'DESIGN_CHANGE') {
        t.haveRedesign = '0'
      }
      return t
    },
    showRedesign() {
      return !['ARTIFICIAL', 'DESIGN_CHANGE'].includes(this.detail.taskType)
    },
    // 是否显示预计完成时间
    showTime() {
      // 2.任务类型为“设计变更”：任务分配时，不显示“预计设计完成时间”字段
      // 7.任务类型为重复测绘：任务分配时，不显示“预计设计完成时间”字段
      // 5.任务类型为设计暂停：不显示“预计设计完成时间”字段
      // 6.任务类型为设计恢复: 不显示“预计设计完成时间”字段
      return !['DESIGN_CHANGE', 'REPEATED_MAPPING', 'DESIGN_PAUSE', 'DESIGN_REGAIN'].includes(this.detail.taskType)
    }
  },
  watch: {
    detail(v) {
      if (v.taskType === 'DESIGN_APPLICATION') {
        this.fillFormData(v, null, 'dheadExpectCompleteTime', 'marketExpectCompleteTime')
      } else if (['DESIGN_CHANGE'].includes(v.taskType)) {
        this.fillFormData(v, ['dheadPicDesignType', 'shopPicDesignType'])
      } else if (['DRAWING_TRIGGER'].includes(v.taskType)) {
        this.fillFormData(v, ['dheadPicDesignType', 'shopPicDesignType'])
        this.$set(this.formData, 'distributeResult', 'A')
        // 3.3门头图纸设计类型、卖场图纸设计类型根据来源图纸的设计类型自动填充下一阶段图纸类型：
        // 卖场图纸类型先后顺序：规划图→摆场图→施工图；
        // 门头图纸类型先后顺序：排版图→施工图；
        let d = ['GH', 'BC', 'SG']
        let i = d.indexOf(v.shopPicDesignType)
        if (i !== -1 && i < d.length - 1) {
          this.$set(this.formData, 'shopPicDesignType', d[i + 1])
        }
        d = ['PB', 'SG']
        i = d.indexOf(v.dheadPicDesignType)
        if (i !== -1 && i < d.length - 1) {
          this.$set(this.formData, 'dheadPicDesignType', d[i + 1])
        }
      } else if (['RESURVEY', 'DESIGN_PAUSE', 'DESIGN_REGAIN'].includes(v.taskType)) {
        // 4.门店复尺：同图纸触发生成逻辑，门头图纸设计类型、卖场图纸设计类型为空，可不填；
        // 5.设计暂停：同图纸触发生成逻辑，门头图纸设计类型、卖场图纸设计类型为空，可不填；
        // 6.设计恢复：同图纸触发生成逻辑，门头图纸设计类型、卖场图纸设计类型为空，可不填；
        this.fillFormData(v, ['dheadPicDesignType', 'shopPicDesignType'])
        this.$set(this.formData, 'distributeResult', 'A')
      } else {
        // 7.手工新增：同图纸触发生成逻辑，但设计范围字段需手工填充，且控制必填；预计完成时间手工填充，图纸设计类型手工填充，控制必填；
        this.fillFormData(v)
        this.$set(this.formData, 'distributeResult', 'A')
      }
      this.fillData(this.taskDetail, this.designDetail)
    }
  },
  created() {
    this.getDetail()
    this.getDataDict()
  },
  methods: {
    async getDetail() {
      await getShopDesignTaskInfo(this.$route.query.id).then(res => {
        this.taskDetail = res.data
        shopConstructPage(res.data.constCode).then(res => {
          this.shopDetail = res.data.records.length > 0 ? res.data.records[0] : {}
        })
        if (this.taskDetail.taskType === 'DRAWING_TRIGGER') {
          getPicturePage(this.taskDetail.sourceCode).then(data => {
            this.picDetail = data
          })
        }
        // 获取设计信息
        getShopDesignInfo(res.data.constCode).then(res => {
          this.designDetail = res.data
        })
      })
      if (this.taskDetail.taskType === 'DESIGN_CHANGE') {
        await basicsInfo(this.$route.query.id).then(res => {
          this.wholeInfo = res.data
        })
      } else {
        // 获取全部详情  设计变更报错
        await getShopDesignTaskWholeInfo(this.$route.query.id).then(res => {
          this.wholeInfo = res.data
        })
      }
    },
    fillData(task, design) {
      if (['DESIGN_APPLICATION', 'DESIGN_CHANGE', 'DRAWING_TRIGGER'].includes(task.taskType)) {
        // 1.2若任务分配结果为“分配”，则“任务终止原因”不显示，设计范围默认填充当前门店建设项目号对应的门店建设范围，不允许修改，其余字段手工填充，且均控制必填，提交后，进度值变更为“待处理”，相关字段保存至设计基础信息表
        // 2.3设计单位默认取设计信息中的值，可修改
        // 3.2设计单位默认取设计信息中的值
        this.$set(this.taskDetail, 'designRange', design.decorationRange)
      }
    },
    fillFormData(v, exclude, ...keys) {
      for (const key of Object.keys(this.formData)) {
        if (keys.length === 0 || (keys.length > 0 && keys.includes(key))) {
          if (exclude instanceof Array && exclude.includes(key)) continue
          if (v.designRange === 'DOOR' && ['marketExpectCompleteTime', 'shopPicDesignType'].includes(key)) continue
          if ((v.designRange || '').includes('STORES') && ['dheadExpectCompleteTime'].includes(key)) continue
          this.$set(this.formData, key, v[key] || '')
        }
      }
    },
    getDataDict() {
      if (this.PIC_TYPE.length > 0) return Promise.resolve()
      SLMDict('PIC_TYPE').then(res => {
        this.PIC_TYPE = res.data
      })
    },
    changeHandle(v, type) {
      const d = this.detail.designRange || ''
      if (!d.includes('DOOR') && type === 'DOOR') return
      // 2.任务类型为“设计变更”：任务分配时，不显示“预计设计完成时间”字段
      // 4.任务类型为门店复尺：不变更预计完成时间；
      // 5.任务类型为设计暂停：选择变更图纸时，不变更预计设计完成时间，但记录暂停时间；
      // 7.任务类型为重复测绘：任务分配时，不显示“预计设计完成时间”字段
      if (['DESIGN_CHANGE', 'RESURVEY', 'DESIGN_PAUSE', 'REPEATED_MAPPING'].includes(this.detail.taskType)) return
      // 与上面条件有重复
      if (!this.showTime) return
      this.setTime(type, v)
    },
    async setTime(type, v) {
      await this.getDataDict()
      let label = ''
      if (v !== undefined) {
        for (const item of this.PIC_TYPE) {
          if (item.dictCode === v) {
            label = item.dictName
          }
        }
      }
      const bizType = []
      let key
      if (type === 'DOOR') {
        key = 'dheadExpectCompleteTime'
        bizType.push('C')
      } else {
        // 01 成品
        // 02 全屋定制
        // 03 整体橱柜
        // 04 卫浴

        // PRODUCT 成品
        // CUSTOMIZED 全屋定制
        // CUPBOARD 整体橱柜
        // BATHROOM 卫浴
        // MODEL 样板间
        key = 'marketExpectCompleteTime'
        const t = this.detail.applyBizType || this.detail.designBizType || this.detail.shopBizType || this.detail.decorationRange || ''
        if (t.includes('01') || t.includes('A') || t.includes('PRODUCT')) {
          bizType.push('A')
        }
        if (t.includes('02') || t.includes('03') || t.includes('04') || t.includes('B') || t.includes('CUSTOMIZED') || t.includes('CUPBOARD') || t.includes('BATHROOM') || t.includes('MODEL')) {
          bizType.push('B')
        }
      }
      postConfigTimeLimitPage(type, label, bizType.join(',')).then(res => {
        const data = res.data.records
        let area = this.detail.doorHeadPicArea || 0
        if (type !== 'DOOR') {
          area = (this.detail.softwareSumArea || 0) + (this.detail.suiteSumArea || 0)
        }
        let day = 0
        if (v === 'SG' || v === 'XG') {
          day = Math.max(0, ...data.filter(e => {
            return e.minArea <= area && e.maxArea >= area
          }).map(e => e.timeLimit))
        } else if (v === 'BC' || v === 'GH' || v === 'PB') {
          day = data.filter(e => {
            return e.minArea <= area && e.maxArea >= area
          }).map(e => e.timeLimit).reduce((pre, cur) => {
            return pre + cur
          }, 0)
        }
        const now = new Date()
        const time = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime() + day * 24 * 3600 * 1000
        this.$set(this.formData, key, this.$parseTime(time))
      })
    },
    cancelHandle() {
      this.$store.dispatch('views/goFirst')
    },
    submitHandle() {
      const data = { ...this.taskDetail, ...this.formData }
      return this.$refs.form.validate().then(() => {
        return putTaskAllocation(data).then(res => {
          this.$message.success('提交成功！')
          this.$store.dispatch('views/goFirst')
        })
      })
    },
    async toSource(v) {
      const { path, query } = await getPath(this.detail.taskType, v)
      if (!path) return
      query ? query.time = new Date().getTime() : ''
      this.$store.dispatch('views/goPage', { path, query })
    },
    // 获取外部组织编码
    changeUnitHandle(v) {
      this.$set(this.formData, 'otherCode', v.otherCode || '')
    }
  }
}
</script>
